package utils

import (
	"fmt"

	"net/http"

	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/redis"
	"github.com/gin-gonic/gin"
)

var router *gin.Engine

func SetupRouter() *gin.Engine {
	router = gin.Default()

	//Session配置，Redis存储
	name := Config.Section("session").Key("name").String()
	maxage, err := Config.Section("session").Key("maxage").Int()
	redishost := Config.Section("session").Key("redishost").String()
	redispsw := Config.Section("session").Key("redispsw").String()

	if err != nil {
		fmt.Println("session.maxage error")
		maxage = 14400
	}
	store, err := redis.NewStore(10, "tcp", redishost, redispsw, []byte("secret"))
	if err != nil {
		panic("redis.NewStore error")
	}
	store.Options(sessions.Options{
		// Path: "/",
		MaxAge:   maxage,
		Secure:   false, //https 时使用
		HttpOnly: true,  //true:JS脚本无法获取cookie信息
	})
	router.Use(sessions.Sessions(name, store))

	//静态目录配置
	router.Static("/public", "public")

	//模板
	router.LoadHTMLGlob("view/**/*")

	router.NoRoute(func(ctx *gin.Context) {
		ctx.HTML(http.StatusNotFound, "404.html", gin.H{
			"url": ctx.Request.URL,
		})
	})
	return router
}
